import { Easing, Tween } from "@tweenjs/tween.js";
import { Script } from "oasis-engine";
import { GameConfig } from "../../GameConfig";

enum TableStatus {
  Enter,
  Idle,
  Shrink,
  Bounce,
}

export class TableScript extends Script {
  private status = TableStatus.Enter;
  private minScale = GameConfig.tableMinScale;
  private defaultScale = 1;
  private deltaScalePerMS =
    (this.defaultScale - this.minScale) / (GameConfig.totalShrinkTime * 1000);

  public needAnimation = true;

  onAwake(): void {}

  onStart(): void {
    if (this.needAnimation) {
      const pos = this.entity.transform.position;
      pos.y = 20;
      this.entity.transform.position = pos;
      new Tween({ posY: this.entity.transform.position.y })
        .to({ posY: 0 }, 800)
        .onUpdate((obj) => {
          const pos = this.entity.transform.position;
          pos.y = obj.posY;
          this.entity.transform.position = pos;
        })
        .easing(Easing.Quartic.In)
        .onComplete(() => {
          this.status = TableStatus.Idle;
        })
        .start();
    } else {
      this.status = TableStatus.Idle;
    }
  }

  press() {
    if (this.status === TableStatus.Idle) {
      this.status = TableStatus.Shrink;
    }
  }

  release() {
    this.status = TableStatus.Bounce;
    new Tween({ scaleY: this.entity.transform.scale.y })
      .to({ scaleY: 1 }, 300)
      .onUpdate((obj) => {
        const scale = this.entity.transform.scale;
        scale.y = obj.scaleY;
        this.entity.transform.scale = scale;
      })
      .easing(Easing.Elastic.Out)
      .onComplete(() => {
        this.status = TableStatus.Idle;
      })
      .start();
  }

  onUpdate(deltaTime: number): void {
    switch (this.status) {
      case TableStatus.Shrink:
        const scale = this.entity.transform.scale;
        scale.y -= this.deltaScalePerMS * deltaTime;
        if (scale.y < this.minScale) {
          this.status = TableStatus.Idle;
        }
        scale.y = scale.y < this.minScale ? this.minScale : scale.y;
        this.entity.transform.scale = scale;
        break;
    }
  }
}
